package com.changsideal.tool;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @ClassName BucketValidator
 * @Description bucket valid class
 * @Author Create by Chansideal.Haosc
 * @Date 2019/6/14 14:51
 * @Version 1.0
 **/
@Slf4j
public final class BucketValidator {
    /**
     * @param client
     * @param bucketName
     */
    public static Boolean checkBucketInfoExits(AmazonS3 client, String bucketName) {
        return checkBucketInfoExits(client, bucketName, null);
    }

    /**
     * @param client
     * @param bucketName
     * @param key
     */
    public static Boolean checkBucketInfoExits(AmazonS3 client, String bucketName, String key) {
        boolean result = true;
        int iState = 0;
        try {
            if (StringUtils.isEmpty(key)) {
                iState = client.doesBucketExistV2(bucketName)
                        ? Constant.BUCKET_EXITS : Constant.BUCKET_NO_EXITS;
            } else {
                iState = client.doesObjectExist(bucketName, key)
                        ? Constant.BUCKET_EXITS : Constant.BUCKET_NO_EXITS;
            }

            if (iState == Constant.BUCKET_EXITS) {
                log.warn("需要创建的bucket已存在:{},状态码{}", bucketName, iState);
                result = false;
            }
        } catch (SdkClientException clientExce) {
            log.error(clientExce.getMessage());
        }
        return result;
    }

    /**
     * @param client
     * @param bucketName
     * @param bucketKey
     * @return
     */
    public static Boolean checkBucketContent(AmazonS3 client, String bucketName, String bucketKey) {
        try {
            S3Object s3Object = client.getObject(bucketName, bucketKey);
            if (s3Object != null) {
                log.warn("根据传入bucketName：{}，bucketKey:{}查询到已相关content组织信息", bucketName, bucketKey);
                return false;
            }
        } catch (SdkClientException clientExce) {
            log.error(clientExce.getMessage());
        }
        return true;
    }

    /**
     * @param client
     * @param bucketName
     * @param bucketKey
     * @return
     */
    public static Boolean checkBucketMetaData(AmazonS3 client, String bucketName, String bucketKey) {
        try {
            ObjectMetadata metadata = client.getObjectMetadata(bucketName, bucketKey);
            if (metadata != null) {
                log.warn("根据传入bucketName：{}，bucketKey:{}查询到已存在相关metaData组织信息", bucketName, bucketKey);
                return true;
            }
        } catch (SdkClientException clientExce) {
            log.error(clientExce.getMessage());
        }
        return false;
    }

    private BucketValidator() {
    }
}
